 <template>
  <!-- 注册 -->
  <div class="register-container">
    <h1 class="title">企业注册</h1>

    <el-form ref="registerForm" :model="registerForm" label-width="100px">
      <el-form-item prop="infoName" label="企业名称" :rules="validateEnterpriceName">
        <el-input v-model="registerForm.infoName" placeholder="企业名称"></el-input>
      </el-form-item>
      <el-form-item
        prop="email"
        label="管理员邮箱"
        :rules="[{ required: true, message: '请输入管理员邮箱', trigger: 'blur' },
                { type: 'email', message: '请输入正确的邮箱', trigger: ['blur', 'change'] }]"
      >
        <el-input v-model="registerForm.email" placeholder="管理员邮箱"></el-input>
      </el-form-item>
      <el-form-item label="机构邀请码">
        <el-input v-model="registerForm.inviteCode" placeholder="机构邀请码，没有可以不填"></el-input>
      </el-form-item>
      <el-form-item label="管理员电话" prop="phone" :rules="validatePhone">
        <el-input v-model="registerForm.phone" placeholder="管理员电话" style="width:70%"></el-input>
        <div style="float: right; width: 30%; height: 32px;">
          <el-button
            @click="sendMessage"
            :disabled="isDisableGetCode"
          >{{countdown === 0 ? '获取验证码' : countdown + '后重试'}}</el-button>
        </div>
      </el-form-item>

      <el-form-item label="短信验证码" prop="phoneCode" :rules="validatePhoneCode">
        <el-input v-model="registerForm.phoneCode" placeholder="短信验证码"></el-input>
      </el-form-item>

      <el-form-item
        prop="password"
        label="密码"
        :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
      >
        <el-input
          v-model="registerForm.password"
          type="password"
          show-password
          placeholder="密码"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码确认" prop="repeatPassword" :rules="validatePass">
        <el-input
          v-model="registerForm.repeatPassword"
          show-password
          type="password"
          placeholder="密码确认"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item
        prop="captcha"
        label="注册验证码"
        :rules="[{ required: true, message: '请输入注册验证码', trigger: 'blur' }    ]"
      >
        <el-input v-model="registerForm.captcha" placeholder="注册验证码" class="code-style"></el-input>
        <div style="float: right; width: 40%; height: 32px; margin-left: 4%;">
          <img
            v-bind:src="codeImg"
            style="width:100%;height:40px;"
            @click="change_captcha('register');"
            data-toggle="tooltip"
            data-placement="top"
            title="看不清，点击换一张"
          >
        </div>
      </el-form-item>
      <el-form-item>
        <el-button class="btn" @click="resetForm('registerForm')">重置</el-button>
        <el-button
          class="btn register-btn add-style"
          type="primary"
          @click="register('registerForm')"
        >注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  getLoginCode,
  register,
  getCode,
  checkCode,
  checkEnterpriceName,
  checkPhone
} from "api/login";
let img_byte = "data:image/png;base64,";
let timer;

export default {
  data() {
    return {
      registerForm: {
        infoName: "",
        email: "",
        phone: "",
        inviteCode: "",
        password: "",
        repeatPassword: "",
        captcha: "", // 注册验证码
        phoneCode: "" // 短信验证码
      },
      countdown: 0,
      isDisableGetCode: false, // 是否禁用获取验证码按钮
      codeImg: "", // 【验证码】图片地址
      // showModel: "login", // 显示注册【register】/登录【login】切换
      // validatePass直接放入html中无法执行new Error()【密码验证】
      validatePass: [
        {
          validator: (rule, value, callback) => {
            if (value === "") {
              return callback(new Error("请再次输入密码"));
            } else if (value !== this.registerForm.password) {
              return callback(new Error("两次输入密码不一致!"));
            } else {
              return callback();
            }
          },
          trigger: "blur"
        }
      ],
      // 【手机号验证】
      validatePhone: [
        { required: true, message: "请输入管理员邮箱", trigger: "blur" },
        {
          validator: (rule, value, callback) => {
            if (value === "") {
              return callback(new Error("请输入手机号码"));
            } else if (!/^1[3|4|5|6|8|7|9][0-9]\d{8}$/.test(value)) {
              return callback(new Error("手机号码格式不正确!"));
            } else {
              checkPhone(value).then(res => {
                console.log(res);
                if (res) {
                  return callback(new Error("手机号码已注册"));
                } else {
                  return callback();
                }
              });
            }
          },
          trigger: "blur"
        }
      ],
      // 【手机验证码验证】
      validatePhoneCode: [
        { required: true, message: "请输入短信验证码", trigger: "blur" },
        {
          validator: (rule, value, callback) => {
            if (!this.registerForm.phone) return;
            checkCode(
              this.registerForm.phone,
              this.registerForm.phoneCode
            ).then(res => {
              if (res.status > 200)
                return callback(new Error("短信验证码错误"));

              return callback();
            });
          },
          trigger: "blur"
        }
      ],
      validateEnterpriceName: [
        { required: true, message: "请输入企业名称", trigger: "blur" },
        {
          validator: (rule, value, callback) => {
            checkEnterpriceName(value).then(res => {
              if (res) {
                return callback("该企业已存在");
              } else {
                return callback();
              }
            });
          },
          trigger: "blur"
        }
      ]
    };
  },
  props: ["showModel", "changeModel"],

  mounted() {
    this.change_captcha();
  },
  methods: {
    // 重复获取验证码
    change_captcha: function(type) {
      this.codeImg = getLoginCode();
    },

    register(formName) {
      this.validate(formName, () => {
        var data = JSON.parse(JSON.stringify(this.registerForm));
        delete data.repeatPassword;
        register(data).then(
          res => {
            this.change_captcha();

            if (res.status > 200) {
              this.$message.error(res.message);
              return;
            }
            this.$message.success("注册成功");
            this.changeModel();
          },
          err => {}
        );
      });
    },

    // 倒计时
    countdownFun(num) {
      this.countdown = --num;

      timer = setTimeout(() => {
        if (num === 0) {
          this.isDisableGetCode = false;
          clearTimeout(timer);
        } else {
          this.countdownFun(num);
        }
      }, 1000);
    },

    // 发送短信
    sendMessage() {
      if (!this.registerForm.phone) return;
      getCode(this.registerForm.phone).then(res => {
        if (res.status > 200) return;
        this.countdown = 60;
        this.countdownFun(60);
        this.isDisableGetCode = true;
        this.$message.success("发送成功");
      });
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    validate: function(formName, callback) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          callback();
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "src/style/mixin";

.register-container {
  margin: 0px auto;
  width: 520px;
  text-align: center;
  .title {
    padding: 20px 0;
    color: #888;
  }

  .code-style {
    width: 230px;
  }
  .btn {
    width: 200px;
  }

  .register-btn {
    background: #1fc3b3;
    color: #fff;
    border: none;
  }
}
</style>
